<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="Spring MVC 进阶应用参数绑定 客户端发送请求时传递的参数默认是键值对格式,Spring MVC通过参数绑定组件将请求的参数串进行类型转换。 Spring MVC使用Controller方法的形参接收请求传来的参数。 1. Spring MVC默认内置的形参类型 HttpServletRequest  HttpServletResponse  HttpSession  Model 一个接口">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring MVC进阶应用">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/17/2016-06-17-springmvc-02/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="Spring MVC 进阶应用参数绑定 客户端发送请求时传递的参数默认是键值对格式,Spring MVC通过参数绑定组件将请求的参数串进行类型转换。 Spring MVC使用Controller方法的形参接收请求传来的参数。 1. Spring MVC默认内置的形参类型 HttpServletRequest  HttpServletResponse  HttpSession  Model 一个接口">
<meta property="og:locale">
<meta property="article:published_time" content="2016-06-16T16:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="SpringMVC">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/17/2016-06-17-springmvc-02/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>Spring MVC进阶应用 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring-MVC-%E8%BF%9B%E9%98%B6%E5%BA%94%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">Spring MVC 进阶应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E6%95%B0%E7%BB%91%E5%AE%9A"><span class="nav-number">1.1.</span> <span class="nav-text">参数绑定</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-Spring-MVC%E9%BB%98%E8%AE%A4%E5%86%85%E7%BD%AE%E7%9A%84%E5%BD%A2%E5%8F%82%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.1.1.</span> <span class="nav-text">1. Spring MVC默认内置的形参类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E7%AE%80%E5%8D%95%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%BB%91%E5%AE%9A"><span class="nav-number">1.1.2.</span> <span class="nav-text">2. 简单数据类型绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-JavaBean%E5%AF%B9%E8%B1%A1%E7%B1%BB%E5%9E%8B%E7%BB%91%E5%AE%9A"><span class="nav-number">1.1.3.</span> <span class="nav-text">3. JavaBean对象类型绑定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-%E9%9B%86%E5%90%88%E7%B1%BB%E5%9E%8B%E7%BB%91%E5%AE%9A"><span class="nav-number">1.1.4.</span> <span class="nav-text">4. 集合类型绑定</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Converter"><span class="nav-number">1.2.</span> <span class="nav-text">Converter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Validation"><span class="nav-number">1.3.</span> <span class="nav-text">Validation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E6%8D%AE%E5%9B%9E%E6%98%BE"><span class="nav-number">1.4.</span> <span class="nav-text">数据回显</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="nav-number">1.5.</span> <span class="nav-text">文件上传</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Interceptor"><span class="nav-number">1.6.</span> <span class="nav-text">Interceptor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RESTful"><span class="nav-number">1.7.</span> <span class="nav-text">RESTful</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JSON"><span class="nav-number">1.8.</span> <span class="nav-text">JSON</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/06/17/2016-06-17-springmvc-02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring MVC进阶应用
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2016-06-17 00:00:00" itemprop="dateCreated datePublished" datetime="2016-06-17T00:00:00+08:00">2016-06-17</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/Java/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="Spring-MVC-进阶应用"><a href="#Spring-MVC-进阶应用" class="headerlink" title="Spring MVC 进阶应用"></a>Spring MVC 进阶应用</h2><h3 id="参数绑定"><a href="#参数绑定" class="headerlink" title="参数绑定"></a>参数绑定</h3><p> 客户端发送请求时传递的参数默认是键值对格式,<code>Spring MVC</code>通过参数绑定组件将请求的参数串进行类型转换。<br> <code>Spring MVC</code>使用Controller方法的形参接收请求传来的参数。</p>
<h4 id="1-Spring-MVC默认内置的形参类型"><a href="#1-Spring-MVC默认内置的形参类型" class="headerlink" title="1. Spring MVC默认内置的形参类型"></a>1. Spring MVC默认内置的形参类型</h4><ul>
<li>HttpServletRequest </li>
<li>HttpServletResponse </li>
<li>HttpSession </li>
<li>Model 一个接口,可以将数据填充到request域对象中。</li>
<li>ModelMap Model接口的实现。</li>
</ul>
<p>这5个对象可以直接通过形参注入并使用。</p>
<h4 id="2-简单数据类型绑定"><a href="#2-简单数据类型绑定" class="headerlink" title="2. 简单数据类型绑定"></a>2. 简单数据类型绑定</h4><p>前端页面表单中的name或者URL中的key与Controller方法中的形参名称一致,即可完成绑定。<br>如果名称不一致,可以使用<code>@RequestParam</code>注解指定名称完成绑定。<br>例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">URL: http:<span class="comment">//xxxxx?SID=1</span></span><br><span class="line"></span><br><span class="line">Controller:</span><br><span class="line"><span class="comment">// 将SID的数据封装到形参id中。</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">update</span> <span class="params">(<span class="meta">@RequestParam(&quot;SID&quot;)</span> Integer id,Model model)</span> </span></span><br></pre></td></tr></table></figure>
<p><strong>RequestParam注解</strong></p>
<ul>
<li>value:参数名,即传入参数的名称。</li>
<li>required:默认为true,表示请求中要有相应的参数,否则报错:Status 400 - Required Integer parameter ‘XXXX’ is not present</li>
<li>defaultValue:默认值,没有同名参数时,则使用默认值。</li>
</ul>
<h4 id="3-JavaBean对象类型绑定"><a href="#3-JavaBean对象类型绑定" class="headerlink" title="3. JavaBean对象类型绑定"></a>3. JavaBean对象类型绑定</h4><p>前端页面表单中的name或者URL中的key与JavaBean中的属性名进行匹配。<br>如果参数名称一致,则将参数绑定到JavaBean中的属性上。<br>如果JavaBean中包装了对象类型,传入参数的名称则需要按照 对象.属性 的格式编写,并且属性要与JavaBean中包装的对象中的属性名称一致。</p>
<h4 id="4-集合类型绑定"><a href="#4-集合类型绑定" class="headerlink" title="4. 集合类型绑定"></a>4. 集合类型绑定</h4><p><strong>数组类型绑定</strong><br>使用checkbox复选框时,会将参数绑定到一个数组中。<br>例如:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">前端页面:</span><br><span class="line">&lt;input type=<span class="string">&quot;checkbox&quot;</span> name=<span class="string">&quot;cId&quot;</span> value=<span class="string">&quot;1&quot;</span>&gt;</span><br><span class="line">&lt;input type=<span class="string">&quot;checkbox&quot;</span> name=<span class="string">&quot;cId&quot;</span> value=<span class="string">&quot;2&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line">Controller:</span><br><span class="line"><span class="comment">// 使用一个数组接收复选框的参数</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> String <span class="title">delete</span> <span class="params">(Integer[] cId,Model model)</span> </span></span><br></pre></td></tr></table></figure>
<p><strong>List集合类型绑定</strong><br>Controller不能直接在形参中定义List,需要在包装类中定义List。<br>页面中的编写格式: list名[index].属性名<br>例如:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;c:forEach items=&quot;$&#123;list&#125;&quot; var=&quot;user&quot; varStatus=&quot;status&quot;&gt;</span><br><span class="line">    <span class="tag">&lt;<span class="name">tr</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">td</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;list[$&#123;status.index&#125;].name&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;user.name&#125;&quot;</span> /&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">tr</span>&gt;</span></span><br><span class="line">&lt;/c:forEach&gt;</span><br></pre></td></tr></table></figure>
<p><strong>Map集合类型绑定</strong><br>Controller不能直接在形参中定义Map,需要在包装类中定义Map。<br>页面中的编写格式:map名[‘key’]<br>例如:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;c:forEach items=&quot;$&#123;list&#125;&quot; var=&quot;user&quot; varStatus=&quot;status&quot;&gt;</span><br><span class="line">    <span class="tag">&lt;<span class="name">tr</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">td</span>&gt;</span><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;map[&#x27;name&#x27;]&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;user.name&#125;&quot;</span> /&gt;</span><span class="tag">&lt;/<span class="name">td</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">tr</span>&gt;</span></span><br><span class="line">&lt;/c:forEach&gt;</span><br></pre></td></tr></table></figure>
<h3 id="Converter"><a href="#Converter" class="headerlink" title="Converter"></a>Converter</h3><p>当请求参数中含有日期类型时,需要自定义一个类型转换器转换成我们需要的日期格式。<br>创建一个类实现Converter接口就可以自定义一个类型转换器。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Converter&lt;需要转换的数据的类型,转换的类型&gt;</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateConverter</span> <span class="keyword">implements</span> <span class="title">Converter</span>&lt;<span class="title">String</span>, <span class="title">Date</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Date <span class="title">convert</span><span class="params">(String source)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">try</span>&#123;</span><br><span class="line">			<span class="comment">// 转换日期格式</span></span><br><span class="line">			SimpleDateFormat format = <span class="keyword">new</span> SimpleDateFormat(<span class="string">&quot;yyyy-MM-dd HH:mm:ss&quot;</span>);</span><br><span class="line">			<span class="keyword">return</span> format.parse(source);</span><br><span class="line">		&#125;<span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 出现异常,则返回null</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>之后需要在处理器适配器中注册Converter</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 注册注解方式的适配器与映射器 --&gt;</span><br><span class="line">&lt;mvc:annotation-driven conversion-service=<span class="string">&quot;conversionService&quot;</span> /&gt;</span><br><span class="line"></span><br><span class="line">&lt;bean id=<span class="string">&quot;conversionService&quot;</span></span><br><span class="line">	class=<span class="string">&quot;org.springframework.format.support.FormattingConversionServiceFactoryBean&quot;</span>&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;converters&quot;</span>&gt;</span><br><span class="line">		&lt;list&gt;</span><br><span class="line">			&lt;!-- 日期类型转换器 --&gt;</span><br><span class="line">			&lt;bean class=<span class="string">&quot;com.sun.ssm.converter.DateConverter&quot;</span>&gt;&lt;/bean&gt;</span><br><span class="line">		&lt;/list&gt;</span><br><span class="line">	&lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<h3 id="Validation"><a href="#Validation" class="headerlink" title="Validation"></a>Validation</h3><p>Spring MVC本身没有实现表现层校验的部分，它本身支持JSR 303校验规范，而这个规范的官方参考实现是hibernate validator。</p>
<p>所以Spring MVC想要实现校验,需要导入Hibernate-validator jar包。</p>
<p>在配置文件中配置validator校验器</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置校验器 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;validator&quot;</span> class=<span class="string">&quot;org.springframework.validation.beanvalidation.LocalValidatorFactoryBean&quot;</span>&gt;</span><br><span class="line">	&lt;!-- 校验器提供者 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;providerClass&quot;</span> value=<span class="string">&quot;org.hibernate.validator.HibernateValidator&quot;</span> /&gt;</span><br><span class="line">	&lt;!-- 指定校验使用的资源文件，在文件中配置校验错误信息，</span><br><span class="line">			如果不指定，默认使用classpath下的ValidationMessages<span class="selector-class">.properties</span> </span><br><span class="line">	--&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;validationMessageSource&quot;</span> ref=<span class="string">&quot;messageSource&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">&lt;!-- 校验错误信息的资源文件 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;messageSource&quot;</span> class=<span class="string">&quot;org.springframework.context.support.ReloadableResourceBundleMessageSource&quot;</span>&gt;</span><br><span class="line">	&lt;!-- 指定文件路径 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;basenames&quot;</span>&gt;</span><br><span class="line">		&lt;list&gt;</span><br><span class="line">			&lt;value&gt;classpath:validationMessages&lt;/value&gt;</span><br><span class="line">		&lt;/list&gt;</span><br><span class="line">	&lt;/property&gt;</span><br><span class="line">	&lt;!-- 指定文件的编码 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;fileEncodings&quot;</span> value=<span class="string">&quot;utf8&quot;</span>/&gt;</span><br><span class="line">	&lt;!-- 资源文件内容缓存的时间，单位秒 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;cacheSeconds&quot;</span> value=<span class="string">&quot;120&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>在处理器适配器中注册Validator</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 注册注解方式的适配器与映射器 --&gt;</span><br><span class="line">&lt;mvc:annotation-driven conversion-service=<span class="string">&quot;conversionService&quot;</span> validator=<span class="string">&quot;validator&quot;</span> /&gt;</span><br></pre></td></tr></table></figure>
<p>在JavaBean中可以使用注解制定校验规则。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ValidationMessages.properties:</span><br><span class="line">    user.username.size.error=用户名长度格式为<span class="number">1</span>-<span class="number">10</span>之间</span><br><span class="line"></span><br><span class="line">JavaBean:</span><br><span class="line"> <span class="meta">@Size(min=1,max=10,message=&quot;&#123;user.username.size.error&#125;&quot;)</span></span><br><span class="line"> <span class="keyword">private</span> String username;</span><br></pre></td></tr></table></figure>
<p>Controller中在需要检验的形参前使用<code>@Validated</code>注解,并在形参中注入一个BindingResult对象接收校验错误信息。<br><code>@Validated</code>注解和BindingResult顺序是固定的。(<code>@Validated</code>在前)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/updateUser&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">updateUser</span><span class="params">(<span class="meta">@Validated</span> User user,BindingResult bindingResult,Model model)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断是否有校验错误信息,如果有则代表校验未通过</span></span><br><span class="line">	<span class="keyword">if</span>(bindingResult.hasErrors())&#123;</span><br><span class="line">	    <span class="comment">// 获得校验错误信息集合</span></span><br><span class="line">		List&lt;ObjectError&gt; allErrors = bindingResult.getAllErrors();</span><br><span class="line">		<span class="comment">// 将校验错误信息集合存入request域中</span></span><br><span class="line">		model.addAttribute(<span class="string">&quot;errors&quot;</span>, allErrors);</span><br><span class="line">			</span><br><span class="line">		<span class="comment">//检验未通过,重新跳转到修改页面</span></span><br><span class="line">		<span class="keyword">return</span> <span class="string">&quot;updateUser&quot;</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>分组校验</strong></p>
<p>因为校验规则是在JavaBean中定义的,所以当同一个JavaBean需要被多个Controller使用时,可能根据需求需要不同的校验。</p>
<p>在这种情况下,可以使用一个标识作用的接口进行分组。</p>
<p>定义一个空接口作为分组的标识:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ValidationGroup</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在JavaBean中使用分组:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Size(min=1,max=10,message=&quot;&#123;user.username.size.error&#125;&quot;,groups=&#123;ValidationGroup.class&#125;)</span></span><br><span class="line"><span class="keyword">private</span> String username;</span><br></pre></td></tr></table></figure>
<p>在Controller中使用分组校验:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/updateUser&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">updateUser</span><span class="params">(<span class="meta">@Validated(value=&#123;ValidationGroup.class&#125;)</span> User user,</span></span></span><br><span class="line"><span class="function"><span class="params">                            BindingResult bindingResult,Model model)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断是否有校验错误信息,如果有则代表校验未通过</span></span><br><span class="line">	<span class="keyword">if</span>(bindingResult.hasErrors())&#123;</span><br><span class="line">	    <span class="comment">// 获得校验错误信息集合</span></span><br><span class="line">		List&lt;ObjectError&gt; allErrors = bindingResult.getAllErrors();</span><br><span class="line">		<span class="comment">// 将校验错误信息集合存入request域中</span></span><br><span class="line">		model.addAttribute(<span class="string">&quot;errors&quot;</span>, allErrors);</span><br><span class="line">			</span><br><span class="line">		<span class="comment">//检验未通过,重新跳转到修改页面</span></span><br><span class="line">		<span class="keyword">return</span> <span class="string">&quot;updateUser&quot;</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>主要的验证注解如下:</p>
<table>
<thead>
<tr>
<th>注解</th>
<th>适用的数据类型</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>@AssertFalse</td>
<td>Boolean, boolean</td>
<td>验证注解的元素值是false</td>
</tr>
<tr>
<td>@AssertTrue</td>
<td>Boolean, boolean</td>
<td>验证注解的元素值是true</td>
</tr>
<tr>
<td>@DecimalMax（value=x）</td>
<td>BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.</td>
<td>验证注解的元素值小于等于@ DecimalMax指定的value值</td>
</tr>
<tr>
<td>@DecimalMin（value=x）</td>
<td>BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.</td>
<td>验证注解的元素值小于等于@ DecimalMin指定的value值</td>
</tr>
<tr>
<td>@Digits(integer=整数位数, fraction=小数位数)</td>
<td>BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.</td>
<td>验证注解的元素值的整数位数和小数位数上限</td>
</tr>
<tr>
<td>@Future</td>
<td>java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.</td>
<td>验证注解的元素值（日期类型）比当前时间晚</td>
</tr>
<tr>
<td>@Max（value=x）</td>
<td>BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.</td>
<td>验证注解的元素值小于等于@Max指定的value值</td>
</tr>
<tr>
<td>@Min（value=x）</td>
<td>BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number.</td>
<td>验证注解的元素值大于等于@Min指定的value值</td>
</tr>
<tr>
<td>@NotNull</td>
<td>Any type</td>
<td>验证注解的元素值不是null</td>
</tr>
<tr>
<td>@Null</td>
<td>Any type</td>
<td>验证注解的元素值是null</td>
</tr>
<tr>
<td>@Past</td>
<td>java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.</td>
<td>验证注解的元素值（日期类型）比当前时间早</td>
</tr>
<tr>
<td>@Pattern(regex=正则表达式, flag=)</td>
<td>String. Additionally supported by HV: any sub-type of CharSequence.</td>
<td>验证注解的元素值与指定的正则表达式匹配</td>
</tr>
<tr>
<td>@Size(min=最小值, max=最大值)</td>
<td>String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.</td>
<td>验证注解的元素值的在min和max（包含）指定区间之内，如字符长度、集合大小</td>
</tr>
<tr>
<td>@Valid</td>
<td>Any non-primitive type（引用类型）</td>
<td>验证关联的对象，如账户对象里有一个订单对象，指定验证订单对象</td>
</tr>
<tr>
<td>@NotEmpty</td>
<td>CharSequence,Collection, Map and Arrays</td>
<td>验证注解的元素值不为null且不为空（字符串长度不为0、集合大小不为0）</td>
</tr>
<tr>
<td>@Range(min=最小值, max=最大值)</td>
<td>CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types</td>
<td>验证注解的元素值在最小值和最大值之间</td>
</tr>
<tr>
<td>@NotBlank</td>
<td>CharSequence</td>
<td>验证注解的元素值不为空（不为null、去除首位空格后长度为0），不同于@NotEmpty，@NotBlank只应用于字符串且在比较时会去除字符串的空格</td>
</tr>
<tr>
<td>@Length(min=下限, max=上限)</td>
<td>CharSequence</td>
<td>验证注解的元素值长度在min和max区间内</td>
</tr>
<tr>
<td>@Email</td>
<td>CharSequence</td>
<td>验证注解的元素值是Email，也可以通过正则表达式和flag指定自定义的email格式</td>
</tr>
</tbody></table>
<h3 id="数据回显"><a href="#数据回显" class="headerlink" title="数据回显"></a>数据回显</h3><p>Spring MVC默认支持数据回显。</p>
<p>Spring MVC会在Controller返回之前,自动将形参中的JavaBean放入Request域中,默认名称为类名首字母小写。<br>只要前端页面动态获取数据的key与JavaBean名称一致,即可完成数据回显。<br>如果名称不一致,也可以用<code>@ModelAttribute</code>注解指定形参放入Request域中的key名。</p>
<h3 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h3><p>Spring MVC使用Multipart解析器完成文件上传,而Multipart解析器需要依赖以下2个jar包:</p>
<ul>
<li>commons-fileupload</li>
<li>commons-io</li>
</ul>
<p><strong>配置Multipart解析器</strong></p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=<span class="string">&quot;multipartResolver&quot;</span> class=<span class="string">&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span>&gt;</span><br><span class="line">    &lt;!-- 限制上传文件的最大长度 --&gt;</span><br><span class="line">    &lt;property name=<span class="string">&quot;maxUploadSize&quot;</span> value=<span class="string">&quot;10*1024*1024&quot;</span>/&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>需要在Controller形参中注入一个MultipartFile对象接收文件,该对象名字要与传入的文件名相同。<br><strong>文件上传示例</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 判断是否上传了文件</span></span><br><span class="line"><span class="keyword">if</span>(file!= <span class="keyword">null</span>)&#123;</span><br><span class="line">		<span class="comment">//原始文件名称</span></span><br><span class="line">		String fileName = file.getOriginalFilename();</span><br><span class="line">		<span class="comment">//判断文件名是否为空</span></span><br><span class="line">		<span class="keyword">if</span>(fileName != <span class="keyword">null</span> &amp;&amp; !<span class="string">&quot;&quot;</span>.equals(fileName))</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="comment">// 文件存放的路径</span></span><br><span class="line">			String path = <span class="string">&quot;D:\\temps\\&quot;</span>;</span><br><span class="line">		    <span class="comment">// 判断文件存放路径是否存在</span></span><br><span class="line">		    File dirFile = <span class="keyword">new</span> File(path);</span><br><span class="line">		    <span class="comment">// 文件夹不存在,自动创建一个文件夹</span></span><br><span class="line">		    <span class="keyword">if</span>(!dirFile.exists()) &#123;</span><br><span class="line">		        dirFile.mkdirs();</span><br><span class="line">		    &#125;</span><br><span class="line">		    <span class="comment">// 使用UUID拼接一个唯一文件名</span></span><br><span class="line">			String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf(<span class="string">&quot;.&quot;</span>));</span><br><span class="line">			<span class="comment">//新的文件</span></span><br><span class="line">			File newFile = <span class="keyword">new</span> File(path+newFileName);</span><br><span class="line">			<span class="comment">//把上传的文件保存成一个新的文件</span></span><br><span class="line">			file.transferTo(newFile);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Interceptor"><a href="#Interceptor" class="headerlink" title="Interceptor"></a>Interceptor</h3><p>Spring MVC的拦截器是针对处理器进行拦截的,当HandlerMapping查找处理器时,会被拦截器拦截。</p>
<p>可以通过实现HandlerIntercepter接口,自定义一个拦截器。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyHandlerInterceptor</span> <span class="keyword">implements</span> <span class="title">HandlerInterceptor</span></span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Handler执行前调用,返回值为true则放行,false则不放行。</span></span><br><span class="line">	<span class="comment">// 应用场景:登录验证,权限授权</span></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">preHandle</span><span class="params">(HttpServletRequest request,HttpServletResponse response, </span></span></span><br><span class="line"><span class="function"><span class="params">	                    Object handler)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		</span><br><span class="line">		</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// Handler开始执行,并且在返回ModelAndView之前调用</span></span><br><span class="line">	<span class="comment">// 应用场景:操作ModelAndView对象</span></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postHandle</span><span class="params">(HttpServletRequest request,HttpServletResponse response, Object handler,</span></span></span><br><span class="line"><span class="function"><span class="params">			ModelAndView modelAndView)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// Handler执行完后调用</span></span><br><span class="line">	<span class="comment">// 应用场景:异常处理、日志</span></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterCompletion</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">			HttpServletResponse response, Object handler, Exception ex)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">		</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>配置拦截器</strong></p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置全局拦截器 --&gt;</span><br><span class="line">&lt;mvc:interceptors&gt;</span><br><span class="line">	&lt;mvc:interceptor&gt;</span><br><span class="line">		&lt;!-- <span class="comment">/**表示所有URL和子URL路径 --&gt;</span></span><br><span class="line"><span class="comment">		&lt;mvc:mapping path=&quot;/**&quot; /&gt;</span></span><br><span class="line"><span class="comment">		&lt;bean class=&quot;com.sun.interceptor.MyHandlerInterceptor&quot; /&gt;</span></span><br><span class="line"><span class="comment">	&lt;/mvc:interceptor&gt;</span></span><br><span class="line"><span class="comment">&lt;/mvc:interceptors&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>拦截器的执行顺序</strong></p>
<ul>
<li>preHandle()为正向顺序执行,postHandle()和afterCompletion()为逆向顺序执行。</li>
<li>如果第一个拦截器返回值为false,那它之后所有的拦截器都不会执行。</li>
<li>如果一个拦截器返回值为false,那么它的postHandle()和afterCompletion()都不会执行。</li>
<li>只要有一个拦截器的返回值为false,则所有拦截器的postHandle()都不会执行。</li>
</ul>
<h3 id="RESTful"><a href="#RESTful" class="headerlink" title="RESTful"></a>RESTful</h3><blockquote>
<p>一种软件架构风格，设计风格而不是标准，只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁，更有层次，更易于实现缓存等机制。</p>
</blockquote>
<p>实现REST风格需要在DispatcherServlet中将url映射模式改为 / </p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;servlet-mapping&gt;</span><br><span class="line">    &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt;</span><br><span class="line">    &lt;url-pattern&gt;/&lt;/url-pattern&gt;</span><br><span class="line">&lt;/servlet-mapping&gt;</span><br></pre></td></tr></table></figure>
<p>但是当映射模式为/时会把静态资源一起拦截,需要配置才能访问静态资源。</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;mvc:resources location=<span class="string">&quot;/js/&quot;</span> mapping=<span class="string">&quot;/js/**&quot;</span>/&gt;</span><br><span class="line">&lt;mvc:resources location=<span class="string">&quot;/css/&quot;</span> mapping=<span class="string">&quot;/css/**&quot;</span>/&gt;</span><br><span class="line">&lt;mvc:resources location=<span class="string">&quot;/jquery/&quot;</span> mapping=<span class="string">&quot;/jquery/**&quot;</span>/&gt;</span><br></pre></td></tr></table></figure>
<p>Springmvc会把mapping映射到ResourceHttpRequestHandler，这样静态资源在经过DispatcherServlet转发时就可以找到对应的Handler了。</p>
<p><strong>在Controller中实现RESTful</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/update/&#123;id&#125;&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">update</span><span class="params">(<span class="meta">@PathVariable</span> Integer id,Model model)</span></span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>@PathVariable</code>:将URL中的模板变量映射到形参上,如果形参与模板变量名称不一致,可以使用value=” “设置为模板变量的名称完成映射。</li>
<li>{id}:模板变量。例如URL为 xxxx/update/1,模板变量update/{id}就可以将1封装到{id}中。</li>
</ul>
<h3 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h3><p>Spring MVC默认使用MappingJacksonHttpMessageConverter对json数据进行转换，所以需要导入Jackson的jar包。</p>
<p>Spring MVC可以使用2个注解完成JSON数据的交互操作。</p>
<ul>
<li><code>@RequestBody</code>:如果请求参数传入的是json数据,使用<code>RequestBody</code>可以将json转换为java对象。</li>
<li><code>@ResponseBody</code>:将返回值的java对象转换为json输出。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/Java/" rel="tag"># Java</a>
              <a href="/yuwanzi.io/tags/SpringMVC/" rel="tag"># SpringMVC</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/15/2016-06-15-springmvc-process/" rel="prev" title="Spring MVC原理及流程">
                  <i class="fa fa-chevron-left"></i> Spring MVC原理及流程
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/19/2016-06-19-lucene/" rel="next" title="使用Lucene实现全文检索">
                  使用Lucene实现全文检索 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
